package com.simplegovern.authority.action;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.simpleframe.security.AuthorityContext;
import com.simpleframe.security.Module;
import com.simpleframe.web.action.CrudActionSupport;
import com.simplegovern.authority.SysActiontype;
import com.simplegovern.authority.SysRole;
import com.simplegovern.authority.service.ActiontypeService;
import com.simplegovern.authority.service.RoleService;

@Scope("prototype")
@Namespace("/role")
@Action("/role/role")
public class RoleAction extends CrudActionSupport  {
	@Autowired
	private RoleService roleService;
	@Autowired
	private ActiontypeService actiontypeService;
	private SysRole role;
	private List<Module> modules;
	private Long[] actionIds;

	@Override
	public String main(){
		System.err.println("---------");
		return MAIN;
	}
	
	@Override
	public String grid() throws Exception {
		System.err.println("----00-");
		page = roleService.getPage(getSearcher());
		return GRID;
	}
	
	@Override
	public String create() throws Exception {
		setSaveMode();
		modules = AuthorityContext.getModules();
		return EDIT;
	}
	
	@Override
	public String edit() throws Exception {
		setUpdateMode();
		role = roleService.getById(role.getId());
		modules = AuthorityContext.getModules(role.getId());
		return EDIT;
	}
	
	@Override
	public String save() throws Exception {
		roleService.create(role,actionIds);
		//添加角色和Action的关联
		//刷新内存
		roleService.addRoleCache(role);
		
		addMessage("角色添加成功");
		return null;
	}
	
	public String update() throws Exception {
		//SysRole update = roleService.getById(role.getId());
		roleService.update(role,actionIds);
		//刷新内存
		roleService.addRoleCache(role);
		addMessage("角色修改成功");
		return null;
	}
	
	public void prepareUpdate() throws Exception {
		role = roleService.getById(getId());
	}
	
	public void validator() throws Exception {
		System.out.println("执行验证");
	}
	
	@Override
	public String delete() throws Exception {
		roleService.deletes(ids);
		addMessage("删除成功");
		return null;
	}
	
	//setters and getters
	
	public void setRole(SysRole role) {
		this.role = role;
	}
	
	public SysRole getRole() {
		return role;
	}
	
	public List<Module> getModules() {
		return modules;
	}
	
	public void setActionIds(Long[] actionIds) {
		this.actionIds = actionIds;
	}
}
